package com.iteye.dwangel.util;

import com.littcore.common.BeanManager;
import com.littcore.saap.common.vo.LoginUserVo;
import com.littcore.saap.system.service.IMenuService;
import com.littcore.saap.system.vo.MenuTreeNodeVo;
import com.littcore.shield.vo.ILoginVo;

import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.ext.beans.StringModel;
import freemarker.template.*;

import java.io.IOException;
import java.util.Map;

/**
 * Use this to declare menu bean.
 * Created by simon on 2015/2/5.
 */
public class MenuDirective implements TemplateDirectiveModel {
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        LoginUserVo loginVo;
        Object obj = params.get("user");
        if (obj instanceof StringModel) {
            Object wrapped = ((StringModel)obj).getWrappedObject();
            if(!(wrapped instanceof LoginUserVo)) {
                throw new TemplateException ("User instance not specified", env);
            }
            loginVo = (LoginUserVo) wrapped;
        } else {
            throw new TemplateException ("User instance not specified", env);
        }
        Object varObject = params.get("var");
        if (!(varObject instanceof SimpleScalar)) {
            throw new TemplateException("var not defined",env);
        }
        IMenuService menuService = BeanManager.getBean("menuService", IMenuService.class);
        MenuTreeNodeVo ret = menuService.findTreeByOpPermission(loginVo);
        env.setVariable(((SimpleScalar) varObject).getAsString(), ObjectWrapper.DEFAULT_WRAPPER.wrap(ret.getSubList()));
    }
}
